package web.appeloffre;
import java.util.List;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import persistence.appeloffre.AppelOffre;
import persistence.appeloffre.ReponseAppelOffre;
import persistence.util.HibernateUtil;
import web.HomePage;
import web.Template;

public class ConsultationReponse extends Template {

	private ListView<ReponseAppelOffre> list;
	private Query query;
	private AppelOffre ao;
	private List<ReponseAppelOffre> reponse;

	public ConsultationReponse(AppelOffre ao)
	{
		super();
		this.ao = ao;
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		query = session.createQuery("Select rao from ReponseAppelOffre rao where ao = :code");
		query.setParameter("code", ao);

		reponse = query.list();
		session.close();
		list = new ListView<ReponseAppelOffre>("listview", reponse)
		{
			public void populateItem(ListItem item)
			{
				final ReponseAppelOffre currentRao = (ReponseAppelOffre) item.getModelObject();
				item.add(new Label("prix", "Prix : "+currentRao.getPrix()));
				item.add(new Label("societe", "Fournisseur : "+currentRao.getFournisseur().getSociete()));
				Form<?> validation = new Form<Object>("form")
				{
					public void onSubmit()
					{
						currentRao.setValidation(1);
						AppelOffre currentAo = currentRao.getAo();
						SessionFactory sf = HibernateUtil.getSessionFactory();
						Session session = sf.openSession();
						Transaction t = session.beginTransaction();
						session.update(currentRao);
						session.update(currentAo);
						t.commit();
						session.close();
						setResponsePage(new HomePage("Appel d'offre validée avec succès"));
					}
				};
				item.add(validation);
			}

		};
		add(new Label("titre", "Liste des réponses pour cet appel d'offre"));
		add(list);

	}
}
